<?php
class GenerateMaterialExpenseAction extends CAction {
	public function run() {
		$model = new MaterialExpense();
		$model->expenseDate = date('Y-m-d');
		if (isset($_POST['MaterialExpense'])) {
			$model->attributes = $_POST['MaterialExpense'];
		}
		if (isset($_POST['add']) && !empty($_POST['addMaterialReceiptIds'])) {
			$criteria = new CDbCriteria();
			$criteria
				->addInCondition('id',
					array_diff($_POST['addMaterialReceiptIds'], $model->receiptIds));
			$criteria->addInCondition('materialExpenseId', array(
					null
				));
			$receipts = MaterialReceipt::model()->findAll($criteria);

			foreach ($receipts as $receipt) {
				$model->receiptIds[] = $receipt->id;
			}

		} elseif (isset($_POST['generate'])) {
			$transaction = Yii::app()->db->beginTransaction();
			try {
				if (!$model->save()) {
					throw new CException('保存失败');
				}
				$expenseId = $model->id;
				$criteria = new CDbCriteria();
				$criteria->addInCondition('id', $model->receiptIds);
				$criteria->addInCondition('materialExpenseId', array(
						null
					));
				$receipts = MaterialReceipt::model()->findAll($criteria);
				$projectId = null;
				$count = 0;
				$totalPrice = 0.0;
				foreach ($receipts as $receipt) {
					if ($projectId === null) {
						$projectId = $receipt->projectId;
					} elseif ($projectId != $receipt->projectId) {
						throw new CException('项目必须一样');
					}
					$count++;
					$totalPrice += $receipt->getTotalPrice();
					$receipt->materialExpenseId = $expenseId;
					$receipt->save();
				}
				if ($count == 0) {
					throw new CException('单据不可为空');
				}
				$model->receiptCount = $count;
				$model->totalPrice = $totalPrice;
				$model->save();
				$transaction->commit();
				$this->getController()
					->redirect(array(
						'viewExpense',
						'id' => $expenseId
					));
			} catch (Exception $e) {
				$transaction->rollback();
			}
		}
		$this->getController()->render('generateExpense', array(
				'model' => $model,
			));
	}
}
